<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <html>

    <head>
        <title>首页</title>
        <style>
            /* 页面整体样式 */
            body {
                margin: 0;
                padding: 0;
                font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
                background-color: #f0f2f5;
            }

            /* 导航栏样式 */
            .navbar {
                background: linear-gradient(to right, #3f51b5, #5c6bc0);
                padding: 15px 50px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                z-index: 1000;
            }

            /* 主内容区域样式 */
            .content {
                padding: 100px 50px;
                /* 上边距为导航栏高度 */
                max-width: 1200px;
                margin: 0 auto;
                background-color: #ffffff;
                border-radius: 8px;
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            }

            /* 商品展示样式 */
            .product {
                border: 1px solid #ddd;
                border-radius: 8px;
                padding: 20px;
                margin: 20px 0;
                text-align: center;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
                transition: transform 0.3s ease;
            }

            .product:hover {
                transform: translateY(-5px);
            }

            .product img {
                max-width: 100%;
                height: auto;
                border-radius: 8px;
            }

            .product h3 {
                margin: 15px 0;
                font-size: 1.5em;
                color: #333;
            }

            .product p {
                margin: 5px 0;
                color: #555;
            }

            /* 导航链接样式 */
            .nav-link {
                color: rgba(255, 255, 255, 0.9);
                text-decoration: none;
                font-size: 16px;
                font-weight: 500;
                padding: 8px 16px;
                border-radius: 20px;
                transition: all 0.3s ease;
            }

            .nav-link:hover {
                background-color: rgba(255, 255, 255, 0.2);
                color: #ffffff;
            }

            /* 按钮样式 */
            button {
                background-color: #3f51b5;
                color: white;
                border: none;
                padding: 12px 24px;
                border-radius: 6px;
                cursor: pointer;
                transition: background-color 0.3s ease, transform 0.3s ease;
            }

            button:hover {
                background-color: #303f9f;
                transform: translateY(-3px);
            }

            /* 价格样式 */
            .price {
                color: #ff5722;
                font-weight: bold;
            }

            /* 联系人样式 */
            .contact {
                display: flex;
                align-items: center;
                margin: 5px 0;
                color: #333;
            }

            /* 联系人图标样式 */
            .contact svg {
                width: 16px;
                height: 16px;
                margin-right: 5px;
            }

            /* 分页控件样式 */
            .pagination {
                display: flex;
                justify-content: center;
                align-items: center;
                margin-top: 20px;
            }

            .pagination button {
                background-color: #3f51b5;
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: 20px;
                cursor: pointer;
                margin: 0 5px;
                transition: background-color 0.3s ease, transform 0.3s ease;
                box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            }

            .pagination button:hover {
                background-color: #303f9f;
                transform: translateY(-2px);
            }

            .pagination span {
                font-size: 16px;
                color: #555;
            }

            /* 模态框样式 */
            .modal {
                display: none;
                position: fixed;
                z-index: 1000;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.8);
                display: flex;
                justify-content: center;
                align-items: center;
                transition: opacity 0.3s ease;
            }

            .modal-content {
                background-color: #fff;
                padding: 30px;
                width: 90%;
                max-width: 500px;
                border-radius: 12px;
                box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
                position: relative;
                transform: translateY(0);
                transition: transform 0.3s ease;
            }

            .close {
                position: absolute;
                top: 10px;
                right: 15px;
                cursor: pointer;
                font-size: 24px;
                color: #555;
            }

            .modal-content h2 {
                margin-top: 0;
                margin-bottom: 20px;
                font-size: 24px;
                color: #333;
            }

            .modal-content form input {
                width: calc(100% - 20px);
                padding: 10px;
                margin-bottom: 15px;
                border: 1px solid #ddd;
                border-radius: 5px;
                font-size: 16px;
            }

            .modal-content form button {
                width: 100%;
                padding: 12px;
                margin-top: 10px;
                font-size: 16px;
            }
        </style>
    </head>

    <body>
        <!-- 导航栏 -->
        <div class="navbar">
            <div class="nav-left">
                <a href="index.jsp" class="nav-link">首页</a>
                <a href="car.jsp" class="nav-link">购物车</a>
                <a href="getOrders" class="nav-link">查看订单</a>
                <button class="sell-product-btn">售卖商品</button>
            </div>
            <div class="nav-right">
                <% String username=(String) session.getAttribute("username"); %>
                    <% if (username !=null) { %>
                        <span class="nav-link">欢迎, <%= username %></span>
                        <% } else { %>
                            <a href="login.jsp" class="nav-link">登录</a>
                            <% } %>
                                <a href="logout" class="nav-link">退出</a>
            </div>
        </div>

        <!-- 主内容区域 -->
        <div class="content">
            <h1>商品展示</h1>

            <!-- 商品展示部分 -->
            <div class="product-list"></div>
        </div>

        <div class="pagination">
            <button id="prevPage" onclick="changePage(-1)">上一页</button>
            <span id="pageInfo"></span>
            <button id="nextPage" onclick="changePage(1)">下一页</button>
        </div>

        <!-- 添加商品模态框 -->
        <div id="addShopModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('addShopModal')">&times;</span>
                <h2>售卖商品</h2>
                <form id="addShopForm">
                    <input type="text" id="shopName" name="shopName" placeholder="商品名称" required />
                    <input type="number" id="shopPrice" name="shopPrice" placeholder="价格" step="0.01" required />
                    <input type="text" id="shopContactPerson" name="shopContactPerson" placeholder="联系人" required />
                    <input type="text" id="shopContactPhone" name="shopContactPhone" placeholder="联系电话" required />
                    <button type="button" onclick="submitAddShop()">添加</button>
                    <button type="button" onclick="closeModal('addShopModal')">
                        取消
                    </button>
                </form>
            </div>
        </div>

        <script>
            let currentPage = 1;
            const pageSize = 5;
            let totalShops = 0;

            function changePage(direction) {
                currentPage += direction;
            }

            function updatePagination() {
                const totalPages = Math.ceil(totalShops / pageSize);
                document.getElementById('pageInfo').textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
                document.getElementById('prevPage').disabled = currentPage === 1;
                document.getElementById('nextPage').disabled = currentPage === totalPages;
            }

            // 确保页面加载后绑定事件
            document.addEventListener('DOMContentLoaded', function() {
                document.querySelector('.sell-product-btn').onclick = function () {
                    console.log('Sell product button clicked');
                    const modal = document.getElementById('addShopModal');
                    modal.style.display = 'block';
                    modal.style.top = '50%';
                    modal.style.left = '50%';
                    modal.style.transform = 'translate(-50%, -50%)';
                };
                document.getElementById('addShopModal').style.display = 'none'; // 确保模态框在页面加载时隐藏
            });

            // 添加到购物车
            function addToCart(shopId) {
              <% Boolean loggedIn = (Boolean) session.getAttribute("loggedIn"); %>
              <% if (loggedIn == null || !loggedIn) { %>
                    alert('请先登录');
                    window.location.href = 'login.jsp';
                    return;
              <% } %>

              const url = new URL('http://localhost:8080/untitled_war_exploded/addToCar');
                url.searchParams.append('shopId', shopId);

                fetch(url, {
                    method: 'GET'
                })
                    .then(response => {
                        if (response.ok) {
                            alert('商品已添加到购物车');
                        } else {
                            throw new Error('添加到购物车失败');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert(error.message);
                    });
            }

            // 显示售卖商品的模态框
            document.querySelector('.sell-product-btn').onclick = function () {
                const modal = document.getElementById('addShopModal');
                modal.style.display = 'block';
                modal.style.top = '50%';
                modal.style.left = '50%';
                modal.style.transform = 'translate(-50%, -50%)';
            };

            // 提交新增商品表单
            function submitAddShop() {
                console.log('Submit add shop form');
                const shopName = document.getElementById('shopName').value;
                const shopPrice = document.getElementById('shopPrice').value;
                const shopContactPerson = document.getElementById('shopContactPerson').value;
                const shopContactPhone = document.getElementById('shopContactPhone').value;
                const url = new URL('http://localhost:8080/untitled_war_exploded/addShop');
                url.searchParams.append('shopName', shopName);
                url.searchParams.append('shopPrice', shopPrice);
                url.searchParams.append('shopContactPerson', shopContactPerson);
                url.searchParams.append('shopContactPhone', shopContactPhone);

                fetch(url, {
                    method: 'POST'
                })
                    .then(response => {
                        if (response.ok) {
                            alert('商品添加成功');
                            return response.text();
                        } else {
                            throw new Error('添加商品失败，请重试。');
                        }
                    })
                    .then(data => {
                        console.log('Success:', data);
                        closeModal('addShopModal'); // 关闭模态框
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert(error.message);
                    });
            }

            // 关闭模态框
            function closeModal(modalId) {
                document.getElementById(modalId).style.display = 'none';
            }

            document.addEventListener('DOMContentLoaded', function() {
                fetch('/Mvc_project_war_exploded/shop/list')
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        return response.json();
                    })
                    .then(data => {
                        console.log('Fetched data:', data);
                        const contentDiv = document.querySelector('.product-list');
                        if (!contentDiv) {
                            console.error('Error: .product-list element not found');
                            return;
                        }
                        const productsHtml = data.map(shop => {
                            const { name, price, contactPerson, contactPhone } = shop;
                            return `
                                <div class="product">
                                    <h3>商品名称：${name}</h3>
                                    <p class="price">价格：¥${price}</p>
                                    <p class="contact">联系人：${contactPerson}</p>
                                    <p class="contact">联系电话：${contactPhone}</p>
                                </div>
                            `;
                        }).join('');
                        contentDiv.innerHTML = productsHtml;
                    })
                    .catch(error => {
                        console.error('Error fetching data:', error);
                        alert('获取商品信息失败，请检查服务器响应。');
                    });
            });
        </script>
    </body>

    </html>